package com.gpay.erp.web.control;

import com.gpay.erp.core.dao.page.PageHelper;
import com.gpay.erp.core.dao.page.PagerModel;
import com.gpay.erp.core.system.bean.SysUser;
import com.gpay.erp.services.common.GlobalStatus;
import com.gpay.erp.services.purchase.ApplicationService;
import com.gpay.erp.services.purchase.ApplicationSubService;
import com.gpay.erp.services.purchase.bean.Application;
import com.gpay.erp.services.purchase.bean.ApplicationSub;
import com.gpay.erp.web.util.WebUtil;
import com.gpay.erp.web.vo.ApplicationAdd;
import com.gpay.erp.web.vo.ApplicationDelete;
import com.gpay.erp.web.vo.ChangeStatus;
import com.gpay.erp.web.vo.ResponseInfo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * Created by COMROSE on 2015/8/25 0025. 采购申请模块
 */
@Controller
@RequestMapping("/purchase/")
public class ApplicationController extends BaseController {
    private Log log = LogFactory.getLog(ApplicationController.class);
    @Autowired
    private GlobalStatus globalStatus;
    @Autowired
    private ApplicationService applicationService;
    @Autowired
    private ApplicationSubService applicationSubService;

    // 页面跳转 采购管理
    @RequestMapping("applicationList")
    public String applicationList() {
        return "purchase/applicationList";
    }

    // 页面跳转 采购申请添加
    @RequestMapping("applicationAdd")
    public String addApplication() {
        return "purchase/applicationAdd";
    }

    // 页面跳转 采购更新页面
    @RequestMapping("applicationUpdate")
    public String updateApplication(String id, ModelMap modelMap) {
        modelMap.addAttribute("applicationId", id);
        return "purchase/applicationAdd";
    }

    // 页面跳转 采购明细
    @RequestMapping("applicationView")
    public String viewApplication(String id, ModelMap modelMap) {
        modelMap.addAttribute("applicationId", id);
        return "purchase/applicationView";
    }

    /**
     * 采购申请查询 返回单表list
     *
     * @param application
     * @param pageHelper
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("selectPageApplicationList")
    public void selectPageApplicationList(Application application, PageHelper pageHelper,
                                          HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        log.info("selectPageApplicationList start");
        if(pageHelper.getOrder()==""||null == pageHelper.getOrder())
        {
            pageHelper.setOrder("id");
            pageHelper.setSort("desc");
        }
        RequestContext requestContext = new RequestContext(request);
        ResponseInfo responseInfo = new ResponseInfo();
		application.setFromRow((pageHelper.getPage() - 1) * pageHelper.getRows());
		application.setToRow(pageHelper.getPage() * pageHelper.getRows());
//        application.setFromRow(0);
//        application.setToRow(9);
        application.setSort(pageHelper.getSort());
        application.setOrder(pageHelper.getOrder());
        PagerModel pagerModel = applicationService.selectPageList(application);
        if (pagerModel != null) {
            for (Object hashMap1 : pagerModel.getRows()) {
                Application hashMap = (Application) hashMap1;
                String statusCode = globalStatus.getApplicationStatus(Integer.parseInt(hashMap.getStatus()));
                hashMap.setStatus(statusCode);
            }
            responseInfo.setResult("00010");
            responseInfo
                    .setMessage(requestContext.getMessage("select.success"));
            responseInfo.setObject(pagerModel);
        } else {
            responseInfo.setResult("11111");
            responseInfo.setMessage(requestContext.getMessage("no.data"));
            responseInfo.setObject(pagerModel);
        }
        log.info("selectPageApplicationList end");
        WebUtil.responseToJson(response, responseInfo);
    }

    /**
     * 添加申请子项 点击子项保存按钮
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("saveApplicationSub")
    public void saveApplicationSub(@RequestBody ApplicationAdd applicationAdd,
                                   HttpServletRequest request, HttpServletResponse response) {
        log.info("saveApplicationSub start");
        RequestContext requestContext = new RequestContext(request);
        ResponseInfo responseInfo = new ResponseInfo();
        HttpSession session = request.getSession();
        int insertId = 1;
        SysUser sysUser = (SysUser) session.getAttribute("loginUser");
        if (applicationAdd != null) {
            Application application = applicationAdd.getApplication();
            application.setApplicationNumber(applicationService.getApplicationNumber()); //生成采购申请号
            application.setStatus("1"); //采购新增状态
            application.setAccountName(sysUser.getAccountName());//添加账套信息
            application.setF_account(sysUser.getF_account());
            List<ApplicationSub> applicationSubList = applicationAdd.getApplicationSubList(); //采购申请子项号码
            for (ApplicationSub applicationSub : applicationSubList) {
                applicationSub.setAccountName(sysUser.getAccountName());//添加账套信息
                applicationSub.setF_account(sysUser.getF_account());
                applicationSub.setStatusSub("1");
            }
            insertId = applicationService.saveApplicationSubList(application, applicationSubList);//业务保存
            if (insertId != 1) {
                try {
                    selectApplicationSub(String.valueOf(insertId), request, response);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                responseInfo.setResult("00041");
                responseInfo.setMessage(requestContext.getMessage("add.fail"));
                responseInfo.setObject(insertId);
                WebUtil.responseToJson(response, responseInfo);
            }
        }
        log.info("insertContractSub end");
    }

    /**
     * 点击采购申请子项详细查询
     *
     * @param id
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("selectApplicationSub")
    public void selectApplicationSub(String id,
                                     HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        log.info("selectApplicationSub start");
        RequestContext requestContext = new RequestContext(request);
        ResponseInfo responseInfo = new ResponseInfo();
        if (id == null) {
            id = "1";
        }
        Application application = applicationService.selectById(id);
        String intS = application.getStatus();
        String statusCode = globalStatus.getApplicationStatus(Integer.parseInt(intS));
        application.setStatus(statusCode);
        List<ApplicationSub> listA = applicationSubService.selectListByfid(id);
        for (ApplicationSub applicationSub1 : listA) {
            applicationSub1.setStatusSub(globalStatus.getApplicationStatus(Integer.parseInt(applicationSub1.getStatusSub())));//状态转换
        }
        ApplicationAdd applicationAdd = new ApplicationAdd();
        applicationAdd.setApplication(application);
        applicationAdd.setApplicationSubList(listA);
        if (applicationAdd != null) {
            responseInfo.setResult("00010");
            responseInfo
                    .setMessage(requestContext.getMessage("select.success"));
            responseInfo.setObject(applicationAdd);
        } else {
            responseInfo.setResult("11111");
            responseInfo.setMessage(requestContext.getMessage("no.data"));
            responseInfo.setObject(applicationAdd);
        }
        log.info("selectApplicationSub end");
        WebUtil.responseToJson(response, responseInfo);
    }

    /**
     * 采购申请详细子页面 点击子项提交按钮
     *
     * @param changeStatus 审批通过 status 4;审批不通过 status 3;提交status 2;撤销提交status 1;撤销 status 0
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("saveCommitApplicationSub")
    public void saveCommitApplicationSub(@RequestBody ChangeStatus changeStatus,
                                         HttpServletRequest request, HttpServletResponse response) {
        log.info("saveCommitApplicationSub start");
        RequestContext requestContext = new RequestContext(request);
        ResponseInfo responseInfo = new ResponseInfo();
        if(checkApplicationStatus(changeStatus.getId(),changeStatus.getStatus())) {
            int resptionV = applicationService.updateCommitStatus(changeStatus.getId(), changeStatus.getStatus());
            if (resptionV != 1) {
                try {
                    selectApplicationSub(changeStatus.getId(), request, response);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }else {
            responseInfo.setResult("20001");
            responseInfo.setMessage(requestContext.getMessage("application.service.fail"));
            responseInfo.setObject("1");
            WebUtil.responseToJson(response, responseInfo);
        }
        log.info("saveCommitApplicationSub end");
    }

    /**
     * 采购申请详细子页面 点击子项保存修改按钮
     *修改主标信息
     * 字表数据库表里面有的需要update
     * 数据库没有的需要insert
     * @param applicationAdd 主表和子表的所有信息
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("saveUpdateApplicationSub")
    public void saveUpdateApplicationSub(@RequestBody ApplicationAdd applicationAdd,
                                   HttpServletRequest request, HttpServletResponse response) {
        log.info("saveUpdateApplicationSub start");
        RequestContext requestContext = new RequestContext(request);
        ResponseInfo responseInfo = new ResponseInfo();
        HttpSession session = request.getSession();
        SysUser sysUser = (SysUser) session.getAttribute("loginUser");
        int updateId =1;
        Application application = applicationAdd.getApplication();
        application.setStatus("1");

    if(checkUpdateSave(application.getId())) {
        List<ApplicationSub> applicationSubList = applicationAdd.getApplicationSubList();
        for(ApplicationSub applicationSub:applicationSubList)
        {
            applicationSub.setAccountName(sysUser.getAccountName());
            applicationSub.setF_account(sysUser.getF_account());
            applicationSub.setStatusSub("1");
        }
        updateId = applicationService.saveUpdateApplicationSub(application, applicationSubList);
        if (updateId != 1) {
            try {
                selectApplicationSub(application.getId(), request, response);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }else {
            responseInfo.setResult("20001");
            responseInfo.setMessage(requestContext.getMessage("application.service.fail"));
            responseInfo.setObject(updateId);
            WebUtil.responseToJson(response, responseInfo);
        }
        log.info("saveUpdateApplicationSub end");
    }
    /**
     * 采购申请详细子页面 点击删除一行记录
     */
    @RequestMapping("deleteOneApplicationSub")
    public void deleteOneApplicationSub(@RequestBody ApplicationDelete applicationDelete,
                                        HttpServletRequest request, HttpServletResponse response) {
        log.info("deleteOneApplicationSub start");
        RequestContext requestContext = new RequestContext(request);
        ResponseInfo responseInfo = new ResponseInfo();
        int updateId = 1;
        if(checkUpdateSave(applicationDelete.getApplicationId())) {
            updateId = applicationService.deleteOneApplicationSub(applicationDelete.getApplicationId(), applicationDelete.getApplicationSubIds());
            if (updateId !=1)
            {
                try {
                    selectApplicationSub(applicationDelete.getApplicationId(), request,response);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            responseInfo.setResult("00041");
            responseInfo.setMessage(requestContext.getMessage("application.service.fail"));
            responseInfo.setObject(updateId);
            WebUtil.responseToJson(response, responseInfo);
        }
        log.info("deleteOneApplicationSub end");
    }
    /**
     * 采购审核列表查询 返回单表list
     *
     * @param application
     * @param pageHelper
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("selectPageApplicationCheckList")
    public void selectPageApplicationCheckList(Application application, PageHelper pageHelper,
                                               HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        log.info("selectPageApplicationCheckList start");
        if(pageHelper.getOrder()==""||null == pageHelper.getOrder())
        {
            pageHelper.setOrder("id");
            pageHelper.setSort("desc");
        }
        RequestContext requestContext = new RequestContext(request);
        ResponseInfo responseInfo = new ResponseInfo();
		application.setFromRow((pageHelper.getPage() - 1) * pageHelper.getRows());
		application.setToRow(pageHelper.getPage() * pageHelper.getRows());
        application.setSort(pageHelper.getSort());
        application.setOrder(pageHelper.getOrder());
//        if ("" == application.getStatus() || null == application.getStatus()) {
            application.setStatus("2");
//        }
        PagerModel pagerModel = applicationService.selectPageList(application);
        if (pagerModel != null) {
            for (Object hashMap1 : pagerModel.getRows()) {
                Application hashMap = (Application) hashMap1;
                String statusCode = globalStatus.getApplicationStatus(Integer.parseInt(application.getStatus()));
                hashMap.setStatus(statusCode);
            }
            responseInfo.setResult("00010");
            responseInfo
                    .setMessage(requestContext.getMessage("select.success"));
            responseInfo.setObject(pagerModel);
        } else {
            responseInfo.setResult("11111");
            responseInfo.setMessage(requestContext.getMessage("no.data"));
            responseInfo.setObject(pagerModel);
        }
        log.info("selectPageApplicationCheckList end");
        WebUtil.responseToJson(response, responseInfo);
    }

    public Boolean checkUpdateSave(String id){
        boolean flag = true;
        String reTurnS = applicationService.selectById(id).getStatus(); //当前id访问的实际状态;
        if("2".equals(reTurnS)||"0".equals(reTurnS)||"4".equals(reTurnS)){
            flag = false;
        }
        return flag;
    }
    public Boolean checkApplicationStatus(String id,String status) {
        boolean flag = false;
        String reTurnS = applicationService.selectById(id).getStatus(); //当前id访问的实际状态;

        if("0".equals(reTurnS)||"4".equals(reTurnS))
        {
            return flag =false;
        }
        if("2".equals(reTurnS)){
           if("4".equals(status)||"3".equals(status)||"1".equals(status)){ //可以撤销提交、审批通过、审批不通过
                flag = true;
            }
        }
        if("1".equals(reTurnS)||"3".equals(reTurnS)){
            if("1".equals(status)||"2".equals(status)||"0".equals(status)){  //新增状态 新增子项、删除子项、提交、撤销、保存。
                flag = true;
            }
        }
        return flag;
    }
}
